const Sequelize = require('sequelize')
const dbConfig = require('../config/db.config')

const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorsAliases: false,

  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle
  }
})
// fix
const db = {}

db.Sequelize = Sequelize
db.sequelize = sequelize

// db.tutorials = require('./tutorial.model.local')(sequelize, Sequelize)
db.user = require('./user.model')(sequelize, Sequelize)
db.role = require('./role.model')(sequelize, Sequelize)
db.resource = require('./resource.model')(sequelize, Sequelize)
db.resource = require('./menu.model')(sequelize, Sequelize)
db.refreshToken = require('./refreshToken.model')(sequelize, Sequelize)
// 用户角色表 关联模型 多对多
db.role.belongsToMany(db.user, {
  through: 'user_roles',
  foreignKey: 'roleId',
  otherKey: 'userId'
})
db.user.belongsToMany(db.role, {
  through: 'user_roles',
  foreignKey: 'userId',
  otherKey: 'roleId'
})
// 角色权限表 关联模型 多对多
db.role.belongsToMany(db.resource, {
  through: 'role_resources',
  foreignKey: 'roleId',
  otherKey: 'resourceId'
})

db.user.belongsToMany(db.role, {
  through: 'role_resources',
  foreignKey: 'resourceId',
  otherKey: 'roleId'
})

// 角色菜单表
db.role.belongsToMany(db.resource, {
  through: 'role_menus',
  foreignKey: 'roleId',
  otherKey: 'menuId'
})
db.user.belongsToMany(db.role, {
  through: 'role_menus',
  foreignKey: 'menuId',
  otherKey: 'roleId'
})
db.ROLES = ['user', 'admin', 'moderator']

// Token 刷新
db.refreshToken.belongsTo(db.user, {
  foreignKey: 'userId',
  targetKey: 'id'
})
db.user.hasOne(db.refreshToken, {
  foreignKey: 'userId',
  targetKey: 'id'
})

module.exports = db
